#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QFileDialog>
#include <QGraphicsRectItem>
#include <QGraphicsView>
#include <QMessageBox>
#include <QStandardItemModel> //MVC模式
#include <QTimer>
#include <QWheelEvent>
#include "customtabstyle.h"
#include "mytask.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(timer1,&QTimer::timeout,this,&MainWindow::TIM1_IQ_Handle);
    timer1->setInterval(1000);
    timer1->start();
    //定时器二用于实时监控基站的LED状态
    connect(timer2,&QTimer::timeout,this,&MainWindow::TIM2_IQ_Handle);
    timer2->setInterval(10);

    for(int i =0; i<=20;i++)
    {
        Unit[i].Led = 0;
        Unit[i].Type="基站";
        Unit[i].Active="在线";
        Unit[i].Addr=0;
        Unit[i].timer=0;
    }

    ui->textEdit->setReadOnly(1);
    ui->textEdit->setStyleSheet("border-radius:50px;border: 1px solid #a1a1a1;padding:18px 18px;"
                                "font-size:25px");
    ui->textEdit->setTextColor(Qt::red);
//    ui->textEdit->append("【发送】（0x22）（"+current_date+"） 0x11 0x22");
    ui->textEdit->setTextColor(Qt::blue);
    ui->textEdit->append("系统启动（"+current_date+"）");

    ui->tabWidget->tabBar()->setStyle(new CustomTabStyle);

    //第一次自定义graphicsView子类,nb!
//    graphicsView = new MyGraphicsView(ui->tab_2);
//    graphicsView->setObjectName(QString::fromUtf8("graphicsView11"));
//    graphicsView->setGeometry(QRect(260, 40, 501, 511));

//    QPen pen ;
//    pen.setColor(QColor(0,160,230));
//    QGraphicsScene *scene = new QGraphicsScene;
//    scene->addText("sss");
//    scene->setBackgroundBrush(Qt::blue);
//    m_rectitem->setRect(0,0,80,80);
//    m_rectitem->setPen(pen);
//    m_rectitem->setBrush(QBrush(QColor(255,0,255)));
//    m_rectitem->setFlag(QGraphicsItem::ItemIsMovable);
//    scene->addItem(m_rectitem);
    //QGraphicsTextItem *m_textitem = new QGraphicsTextItem();
//    graphicsView->setScene(scene);

    Unit_Widget_Init();
    Tag_Widget_Init();
    Search_Uart();
    //Tag_Data_Deal(20);

    ui->pushButton->installEventFilter(this);
    ui->label_tag->installEventFilter(this);
    ui->label_tag_2->installEventFilter(this);
    ui->label_tag_3->installEventFilter(this);

    ui->label->setAlignment(Qt::AlignCenter);
    ui->label->hide();

    ui->label_anchor->setAlignment(Qt::AlignCenter);
    ui->label_anchor->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_2->setAlignment(Qt::AlignCenter);
    ui->label_anchor_2->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_3->setAlignment(Qt::AlignCenter);
    ui->label_anchor_3->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_4->setAlignment(Qt::AlignCenter);
    ui->label_anchor_4->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_5->setAlignment(Qt::AlignCenter);
    ui->label_anchor_5->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_6->setAlignment(Qt::AlignCenter);
    ui->label_anchor_6->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_7->setAlignment(Qt::AlignCenter);
    ui->label_anchor_7->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_8->setAlignment(Qt::AlignCenter);
    ui->label_anchor_8->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");
    ui->label_anchor_9->setAlignment(Qt::AlignCenter);
    ui->label_anchor_9->setStyleSheet("border:4px solid red;border-radius:10px;padding:6px 4px;");

    ui->label_tag->hide();
    ui->label_tag->setText(" ");
    ui->label_tag->setStyleSheet("border:1px solid black;border-radius:13px;min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;"
                                 "background:rgb(200,101,102);");
    ui->label_tag_2->hide();
    ui->label_tag_2->setText(" ");
    ui->label_tag_2->setStyleSheet("border:1px solid black;border-radius:13px;min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;"
                                 "background:rgb(104,33,122)");
    ui->label_tag_3->hide();
    ui->label_tag_3->setText(" ");
    ui->label_tag_3->setStyleSheet("border:1px solid black;border-radius:13px;min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;"
                                 "background:rgb(46,139,87);");

    ui->draw_track->setStyleSheet(  //鼠标按下样式
                                    "QPushButton:pressed{"
                                    "background-color:rgb(200,101,102);"
                                    "border-color:rgb(255,255,255,30);"
                                    "border-style:inset;"
                                    "color:rgb(0,0,0);"
                                    "}"
                                    //鼠标悬停样式
                                    "QPushButton:hover{"
                                    "background-color:rgb(255,255,255);"
                                    "border-color:rgb(255,255,255);"
                                    "color:rgba(0,0,0,200);"
                                    "}");

   // ui->label->setStyleSheet("min-width: 16px; min-height: 16px;max-width:26px; max-height: 26px;border-radius: 8px;  border:1px solid black;background:yellow");

//    QString input = "{20;3;(83,7,43,562,0)|(263,4,123,464,1)|(674,1,523,311,1)|;1;(123,2,342,465,0)|}";
//    Uart_Data_Deal(input);
//    Unit_Data_Deal(Anchor_Num+Tag_Num);

//    timer2->start();

    ui->tabWidget->setCurrentIndex(0);
    ui->groupBox->lower();
    ui->tableWidget->lower();
    ui->tabWidget->lower();

}

MainWindow::~MainWindow()
{
    delete ui;
}

//定时器1 用来判断基站或标签是否超时，超时即离线
void MainWindow::TIM1_IQ_Handle()
{
    for(int i = 0 ; i < Anchor_Num+Tag_Num ; i++)
    {
        Unit[i].timer ++ ;
        if(Unit[i].timer > Offline_delay )
        {
            Unit[i].Active = "离线";
            qDebug()<<QString("0x%1 ").arg(Unit[i].Addr,4,16,QChar('0'))<<"offline";
            Unit_Data_Deal(Anchor_Num + Tag_Num);
        }
    }
}

//定时器2 时刻监听 各个标签基站的 checkbox
void MainWindow::TIM2_IQ_Handle()
{
//    ui->label_tag->move(200,200);
//    ui->label_tag->show();
//    ui->label_tag_2->move(70,100);
//    ui->label_tag->show();

    update();
    for(int i = 0 ; i < Anchor_Num+Tag_Num ;i++)
    {
        if(checkBox[i]->checkState() == 2)
        {
            Unit[i].Led = 1;
        }
        else Unit[i].Led = 0;
    }
}

//“搜索”按键
void MainWindow::on_uart_search_button_clicked()
{
    Search_Uart();
}

//“打开”按钮
void MainWindow::on_uart_open_button_clicked()
{
    if(UartOpenFlag)
    {
        ui->uart_box->setDisabled(1);

        //设置串口名字
        MySerial.setPortName(ui->uart_box->currentText());
        qDebug()<<ui->uart_box->currentText();
        //设置波特率
        MySerial.setBaudRate(ui->boud_box->currentText().toInt());
        //设置数据位
        MySerial.setDataBits(QSerialPort::Data8);
        //设置校验位
        MySerial.setParity(QSerialPort::NoParity);
        //设置停止位
        MySerial.setStopBits(QSerialPort::OneStop);
        MySerial.setFlowControl(QSerialPort::NoFlowControl);
        //打开串口
        MySerial.open(QIODevice::ReadWrite);
        qDebug()<<"串口打开成功";
        ui->uart_open_button->setText("关闭串口");
        UartOpenFlag=0;
    }
    else if(!UartOpenFlag)
    {
        MySerial.close();
        ui->uart_open_button->setText("打开串口");
        ui->uart_box->setEnabled(1);
        UartOpenFlag=1;
    }
}

void MainWindow::on_pushButton_clicked()
{

//    QString s = "[1,123,111,200,1]";
//    Uart_Data_Deal__(s);
//    Unit_Data_Deal(Anchor_Num+Tag_Num);

//    QString input = "{20;3;(83,7,43,562,0)|(263,4,123,464,1)|(674,1,523,311,1)|;1;(123,2,42,465,0)|}";
//    Uart_Data_Deal(input);
//    Anchor_Data_Deal(Anchor_Num+Tag_Num);
}

void MainWindow::on_Search_UWB_clicked()
{
    QByteArray uart_write;
    uart_write.append('{');
    uart_write.append('7');
    uart_write.append(',');
    uart_write.append('a');
    uart_write.append('a');
    uart_write.append(',');
    uart_write.append('b');
    uart_write.append('b');
    uart_write.append('}');
    MySerial.write(uart_write);
    uart_write.clear();
    ui->textEdit->setTextColor(Qt::red);
    current_date = current_date_time.toString("yyyy.MM.dd hh:mm:ss");
    ui->textEdit->append("【发送】（"+current_date+"） "+"0x07 0xaa 0xbb");
    ui->textEdit->setTextColor(Qt::blue);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    QCursor *cursor = new QCursor;
    int x=cursor->pos().x();
    int y=cursor->pos().y();


    for(int i = 0 ; i< Tag_Num ; i++)
    {
        if(i==0)
        {
            if(watched == ui->label_tag)
            {
                if(event->type()==QEvent::Enter)
                {
                    ui->label->move(ui->label_tag->pos().x()+125+5,ui->label_tag->pos().y()-5);
                    QString t1 =QString::number(Unit[Anchor_Num+i].X);
                    QString t2 =QString::number(Unit[Anchor_Num+i].Y);
                    ui->label->setText('('+t1+','+t2+')'+"\r\n"+"状态:"+Unit[Anchor_Num].Active);
                    ui->label->show();
                }
                else if(event->type()==QEvent::Leave)
                {
                    ui->label->hide();
                }
            }
        }
        else if(i == 1)
        {
            if(watched == ui->label_tag_2)
            {
                if(event->type()==QEvent::Enter)
                {
                    ui->label->move(ui->label_tag_2->pos().x()+125+5,ui->label_tag_2->pos().y()-5);
                    QString t1 =QString::number(Unit[Anchor_Num+i].X);
                    QString t2 =QString::number(Unit[Anchor_Num+i].Y);
                    ui->label->setText('('+t1+','+t2+')'+"\r\n"+"状态:"+Unit[Anchor_Num].Active);
                    ui->label->show();
                }
                else if(event->type()==QEvent::Leave)
                {
                    ui->label->hide();
                }
            }
        }
    }
    return QMainWindow::eventFilter(watched,event);
}


void MainWindow::resizeEvent(QResizeEvent *event)
{
    QSize oldSize,size;
    oldSize = event->oldSize(); //获取开始的size
    size = event->size();       //获取现在的size
     //获取长宽变化的比率
    qreal ratioW,ratioH;
    ratioW = size.width()/oldSize.width();
    ratioH = size.height()/oldSize.height();
}


int temp=0;
void MainWindow::on_draw_track_clicked()
{
    temp++;
    ui->tabWidget->setCurrentIndex(1);
    if(temp == 1)
    {
        ui->draw_track->setText("关闭");
        track_flag = 1;
        track_draw = 1;
    }
    else
    {
        ui->draw_track->setText("开启");
        track_flag = 0;
        track_draw = 0;
        temp=0;
    }
}

void MainWindow::on_clear_track_clicked()
{
    for (int i = 0 ; i < Tag_Num ; i++)
    {
        track_num[Tag_Num] = 0;
    }
}

void MainWindow::on_data_track_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this,
                                                    tr("保存"),
                                                    "",
                                                    tr("data(*.txt)"));
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QMessageBox::critical(this, "critical", tr("文件保存失败！"),
                              QMessageBox::Yes, QMessageBox::Yes);
    }
    else
    {
        QTextStream stream(&file);
        QString temp;
        for(int j = 0 ; j < Tag_Num ;j++)
        {
            temp.append(QString("Tag%1:").arg(j+1,1,10));
            for (int i = 0 ; i< track_num[j] ; i+=2)
            {
                temp.append( QString::number(TagPoint[0][j])+','+QString::number(TagPoint[0][j+1])+QString("\n") );
                if( i % 50 == 0)
                {
                    stream<<temp;
                    stream.flush();
                    temp.clear();
                }
            }
            stream <<temp;
            temp.clear();
        }
        file.close();
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{

//    QPen pen(QColor(0, 0, 255));
//    //设置笔宽
//     pen.setWidth(5);
//     painter.setPen(pen);
//    painter.drawLine(QPoint(0, 0), QPoint(380, 300));

}



